<template>
  <div class="login-bg">
    <div class="login-wrapper">
      <!-- 左侧宣传栏 -->
      <div class="login-left">
        <div class="brand">
          <img src="@/assets/lgo2222.png" alt="logo" class="brand-logo" />
        </div>
        <h2 class="main-title">{{ $t("接受免费付费调查！") }}</h2>
        <h3 class="sub-title">
          {{ $t("兑换免费PaypalCash，") }}<br />
          {{ $t("比特币和礼品卡！") }}
        </h3>
        <p class="desc">
          {{ $t("从200多种奖励中选择，包括") }}<br />
          {{ $t("亚马逊礼品卡、比特币和PayPal现金") }}
        </p>
        <button class="watch-btn">
          <span class="watch-icon">▶</span> {{ $t("观看以开始") }}
        </button>
        <div class="awards">
          <div class="awards-title">{{ $t("特色奖项") }}</div>
          <div class="awards-list">
            <img src="@/assets/award1.png" alt="award" />
            <img src="@/assets/award2.png" alt="award" />
            <img src="@/assets/award3.png" alt="award" />
            <img src="@/assets/award4.png" alt="award" />
            <img src="@/assets/award5.png" alt="award" />
            <img src="@/assets/award6.png" alt="award" />
          </div>
        </div>
      </div>
      <!-- 右侧注册卡片 -->
      <div class="login-right">
        <div class="card">
          <div class="card-title">{{ $t("加入并开始赚钱") }}</div>
          <div class="welcome-bonus">{{ $t("100分欢迎奖金") }}</div>
          <el-form
            :model="form"
            :rules="rules"
            ref="registerFormRef"
            class="form"
            @submit.prevent="onSubmit"
          >
            <el-form-item :prop="$t('电子邮件')">
              <el-input
                v-model="form.email"
                :placeholder="$t('您的电子邮件')"
                size="large"
              />
            </el-form-item>
            <el-form-item prop="verificationCode">
              <div style="display: flex; gap: 10px; align-items: center">
                <el-input
                  v-model="form.verificationCode"
                  :placeholder="$t('验证码')"
                  size="large"
                />
                <el-button
                  type="primary"
                  :disabled="countdown > 0"
                  @click="sendVerificationCode"
                  size="large"
                >
                  {{ countdown > 0 ? `${countdown}s` : $t("获取代码") }}
                </el-button>
              </div>
            </el-form-item>
            <el-form-item :prop="$t('密码')">
              <el-input
                v-model="form.password"
                type="password"
                :placeholder="$t('密码')"
                size="large"
                show-password
              />
            </el-form-item>
            <el-form-item :prop="$t('确认密码')">
              <el-input
                v-model="form.confirmPassword"
                type="password"
                :placeholder="$t('确认密码')"
                size="large"
                show-password
              />
            </el-form-item>
            <el-button
              type="primary"
              class="signup-btn"
              @click="onSubmit"
              :loading="loading"
              >{{ $t("注册") }}</el-button
            >
          </el-form>
          <div class="login-link">
            {{ $t("已经有账号了？") }}
            <a @click="$router.push('/login')" class="link">{{ $t("登录") }}</a>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import { register, sendMsg } from "../../api/index";
import LanguageSwitcher from "../../components/LanguageSwitcher.vue";
import { ElMessage } from "element-plus";
import { Message, Key, Lock } from "@element-plus/icons-vue";
import { useI18n } from "vue-i18n";
export default {
  name: "Register",
  components: {
    LanguageSwitcher,
  },
  setup() {
    const loading = ref(false);
    const countdown = ref(0);
    const router = useRouter();
    const store = useStore();

    const { t } = useI18n();
    const form = reactive({
      email: "",
      verificationCode: "",
      password: "",
      confirmPassword: "",
      agreeTerms: false,
    });

    const rules = reactive({
      email: [
        { required: true, message: t("请输入邮箱地址"), trigger: "blur" },
        { type: "email", message: t("请输入正确的邮箱格式"), trigger: "blur" },
      ],
      verificationCode: [
        { required: true, message: t("请输入验证码"), trigger: "blur" },
      ],
      password: [
        { required: true, message: t("请输入密码"), trigger: "blur" },
        {
          min: 6,
          max: 20,
          message: t("密码长度在 6 到 20 个字符"),
          trigger: "blur",
        },
      ],
      confirmPassword: [
        { required: true, message: t("请再次输入密码"), trigger: "blur" },
        {
          validator: (rule, value, callback) => {
            if (value !== form.password) {
              callback(new Error(t("两次输入的密码不一致")));
            } else {
              callback();
            }
          },
          trigger: "blur",
        },
      ],
    });

    const registerFormRef = ref(null);

    const sendVerificationCode = async () => {
      if (!form.email) {
        ElMessage.error({
          message: t("请先输入邮箱地址"),
          offset: 100,
          duration: 5000,
        });
        return;
      }

      if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) {
        ElMessage.error({
          message: t("请输入正确的邮箱格式"),
          offset: 100,
          duration: 5000,
        });
        return;
      }

      try {
        // 调用发送验证码API
        const response = await sendMsg({
          username: form.email,
          type: 2,
        });

        if (response.code === 10000) {
          ElMessage.success({
            message: t("验证码已发送"),
            offset: 100,
            duration: 5000,
          });

          // 开始倒计时
          countdown.value = 120;
          const timer = setInterval(() => {
            countdown.value--;
            if (countdown.value <= 0) {
              clearInterval(timer);
            }
          }, 1000);
        } else {
          ElMessage.error({
            message: response.message || t("验证码发送失败，请重试"),
            offset: 100,
            duration: 5000,
          });
        }
      } catch (error) {
        ElMessage.error({
          message: t("验证码发送失败，请重试"),
          offset: 100,
          duration: 5000,
        });
      }
    };

    const onSubmit = async () => {
      if (!registerFormRef.value) return;

      try {
        const valid = await registerFormRef.value.validate();
        if (valid) {
          loading.value = true;
          try {
            let option = {
              username: form.email,
              password: form.password,
              code: form.verificationCode,
            };
            const response = await register(option);
            console.log(response);
            if (response.code === 10000) {
              // 注册成功，重置loading状态
              loading.value = false;
              ElMessage.success({
                message: "Registration successful!",
                offset: 100,
                duration: 5000,
              });
              router.push("/login");
            } else {
              // 注册失败，重置loading状态
              loading.value = false;
              ElMessage.error({
                message:
                  response.message || "Registration failed, please try again",
                offset: 100,
                duration: 5000,
              });
            }
          } catch (error) {
            ElMessage.error({
              message: t("注册失败，请重试"),
              offset: 100,
              duration: 5000,
            });
          } finally {
            loading.value = false;
          }
        }
      } catch (error) {
        ElMessage.error({
          message: t("请检查输入信息"),
          offset: 100,
          duration: 5000,
        });
      }
    };

    // 获取当前语言的文本
    const getCurrentText = (chineseText, englishText) => {
      if (!chineseText || !englishText) return chineseText || englishText || "";
      return store.getters.currentLanguage === "zh" ? chineseText : englishText;
    };

    // 获取logo图片URL
    const logoUrl = computed(() => {
      const shopData = store.getters.shopData;
      const imgUrl = store.state.imgUrl;

      if (shopData && shopData.logo_img) {
        const fullUrl = imgUrl + shopData.logo_img;
        return fullUrl;
      }

      // 如果没有获取到logo_img，则使用默认图片
      return new URL("@/assets/lgo.png", import.meta.url).href;
    });

    return {
      form,
      loading,
      countdown,
      sendVerificationCode,
      onSubmit,
      registerFormRef,
      rules,
      getCurrentText,
      store,
      logoUrl, // 暴露logoUrl给模板使用
    };
  },
};
</script>

<style lang="scss" scoped>
.login-bg {
  min-height: 100vh;
  background-image: url("@/assets/bbbbggg.png");
  background-size: 100% 100%;
  background-repeat: no-repeat;
  display: flex;
  align-items: center;
  justify-content: center;
}
.login-wrapper {
  display: flex;
  width: 100%;
  max-width: 1100px;
  min-height: 600px;
  background: transparent;
  border-radius: 16px;
  box-sizing: border-box;
  padding: 32px;
  gap: 40px;
}
.login-left {
  flex: 1.2;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding-left: 32px;
  color: #222;
  .brand {
    display: flex;
    align-items: center;
    margin-bottom: 32px;
    .brand-logo {
      width: 249px;
      height: 96px;
      margin-right: 16px;
    }
    .brand-title {
      font-size: 32px;
      font-weight: 600;
      letter-spacing: 1px;
    }
  }
  .main-title {
    font-size: 32px;
    font-weight: 800;
    margin-bottom: 16px;
  }
  .sub-title {
    font-size: 28px;
    font-weight: 700;
    margin-bottom: 18px;
    line-height: 1.2;
  }
  .desc {
    font-size: 16px;
    margin-bottom: 24px;
    color: #333;
  }
  .watch-btn {
    background: #4faaff;
    color: #fff;
    border: none;
    border-radius: 24px;
    padding: 12px 32px;
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 32px;
    cursor: pointer;
    box-shadow: 0 4px 16px rgba(79, 170, 255, 0.15);
    .watch-icon {
      font-size: 20px;
      margin-right: 8px;
      vertical-align: middle;
    }
  }
  .awards {
    margin-top: 24px;
    .awards-title {
      font-size: 16px;
      font-weight: 600;
      margin-bottom: 12px;
    }
    .awards-list {
      display: flex;
      gap: 18px;
      img {
        width: 48px;
        height: 32px;
        object-fit: contain;
      }
    }
  }
}
.login-right {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  .card {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 18px;
    box-shadow: 0 8px 32px rgba(79, 170, 255, 0.1);
    padding: 40px 32px;
    min-width: 340px;
    max-width: 370px;
    display: flex;
    flex-direction: column;
    align-items: center;
    .card-title {
      font-size: 24px;
      font-weight: 700;
      margin-bottom: 12px;
      color: #222;
      text-align: center;
    }
    .welcome-bonus {
      background: #ffe6ee;
      color: #ff4d6b;
      font-size: 14px;
      font-weight: 600;
      border-radius: 12px;
      padding: 6px 18px;
      margin-bottom: 24px;
      text-align: center;
    }
    .form {
      width: 100%;
      .el-form-item {
        margin-bottom: 18px;
      }
      .el-input__wrapper {
        background: #f3f8ff;
        border-radius: 12px;
        border: 1px solid #e0e7ff;
      }
      .el-input__inner {
        font-size: 16px;
        color: #222;
      }
    }
    .terms {
      font-size: 13px;
      color: #888;
      margin-bottom: 18px;
      text-align: left;
      .link {
        color: #4faaff;
        text-decoration: underline;
        margin: 0 2px;
      }
    }
    .signup-btn {
      width: 100%;
      height: 48px;
      background: linear-gradient(90deg, #ff4d6b 0%, #ffb86b 100%);
      border: none;
      border-radius: 24px;
      color: #fff;
      font-size: 18px;
      font-weight: 700;
      margin-bottom: 18px;
      cursor: pointer;
    }
    .or {
      color: #888;
      font-size: 15px;
      margin-bottom: 10px;
      text-align: center;
    }
    .login-link {
      font-size: 15px;
      color: #888;
      .link {
        color: #4faaff;
        margin-left: 4px;
        cursor: pointer;
        text-decoration: underline;
      }
    }
  }
}
@media (max-width: 900px) {
  .login-wrapper {
    flex-direction: column;
    gap: 24px;
    padding: 16px;
  }
  .login-left {
    padding-left: 0;
    align-items: center;
    text-align: center;
    .brand {
      justify-content: center;
    }
    .awards-list {
      justify-content: center;
    }
  }
  .login-right {
    .card {
      min-width: 100%;
      max-width: 100%;
      padding: 32px 16px;
    }
  }
}
</style>